<template>
	<view>
		<!-- 选择收货地址的盒子 -->
		<view class="address-choose-box" v-if="JSON.stringify(address)==='{}'">
			<button type="primary" size="mini" class="btn-choose-address" @click="chooseAddress">请选择收货地址+</button>
		</view>
		
		<!-- 渲染收获地址的盒子 -->
		<view class="address-info-box" v-else @click="chooseAddress">
			<view class="row1">
				<view class="row1-left">
					<view class="username">收货人: {{address.userName}}</view>
				</view>
				<viw class="row1-right">
					<view class="phone">
						电话: {{address.telNumber}}
					</view>
					<uni-icons type="arrowright" size="16"></uni-icons>
				</viw>
			</view>
			
			<view class="row2">
				<view class="row2-left">
					收货地址: 
				</view>
				<view class="row2-right">
					{{addStr}}
				</view>
			</view>

		</view>
		<hr></hr>
	</view>
</template>

<script>
	import { mapState, mapMutations, mapGetters } from 'vuex'
	export default {
		name:"my-address",
		data() {
			return {
				// address: {}
			};
		},
		computed: {
			...mapState('m_user', ['address']),
		    ...mapGetters('m_user', ['addStr']),
		},
		methods: {
			...mapMutations('m_user',['updateAddress']),
			async chooseAddress() {
				// 调用小程序提供的chooseAddress方法
				const [err,succ] = await uni.chooseAddress().catch(err => err)
				// 用户成功选择了收货地址
				if (err === null && succ.errMsg === 'chooseAddress:ok') {
					this.updateAddress(succ)
				}
				
				// 用户没有授权 苹果兼容
				if(err && errMsg === 'chooseAddress:fail auth deny' || err.msg === 'chooseAddress: fail authorize no respons') {
					this.reAuth() //重新放弃授权请求
				}	
			},
			async reAuth() {
				const [err2, confirmResult] = await uni.showModal({
						content: "确认",
						cancelText: "取消",
				})
				
				// 弹框异常直接推出
				if (err2) return
				// 点击了取消按钮
				if (confirmResult.cancel) return uni.$showMsg('您取消了授权')
				
				// 如果用户点击了确认按钮，调用uni.openSetting()方法进入授权页面，让用户重新获取授权
				if (confirmResult.confirm) return uni.openSetting({
					// 授权结束，需要对授权的结果做进一步判断
					success: (setttingResult) => {
						// 地址授权的值等于true，提示用户授权成功
						if (setttingResult.authSetting['scope.address']) return uni.$showMsg('授权成功!请选择地址')
						// false：取消了授权
						if (setttingResult.authSetting['scope.address']) return uni.$showMsg('您取消了地址授权')
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	hr {
		border: 2px solid #FA516B;
		margin: 5px 10px;
	}
	
	.address-choose-box {
		height: 90px;
		display: flex;
		align-items: center;
		justify-content: center;
		.btn-choose-address {
			
		}
	}
	
	.address-info-box {
		padding: 10px 10px 0 10px;
		height:70px;
		font-size: 12px;
		.row1 {
			display: flex;
			justify-content: space-between;
			.row1-right {
				display: flex;
			}
		}
		.row2 {
			margin-top: 10px;
			display: flex;
			.row2-left {
				line-height: 14px;
				display: block;
				padding-right: 10px;
			}
		}
	}
</style>
